package com.naizhuai.ui.management;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.naizhuai.Model.ModelProvider;
import com.naizhuai.Model.db.search.SearchDataSourse;
import com.naizhuai.Model.db.search.SearchHistoryBean;
import com.naizhuai.Model.db.search.SearchRepository;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.exception.ServerException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.ManageDividerItemDecoration;
import com.naizhuai.ui.adapter.management.AddTeamAdapterHolder;
import com.naizhuai.ui.adapter.management.SearchUserListHolder;
import com.naizhuai.ui.entity.VirtualChosenBean;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.management.presenter.UserSearchDataApiStoreIml;
import com.naizhuai.ui.mianbusiness.presenter.PublicDataApiStoreIml;
import com.naizhuai.util.AESCrypt;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.ErrorViewCreateUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.NaizhuAILog;

import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;

/**
 * 公司管理搜索界面
 */
public class CompanySearchActivity extends BaseActivity implements View.OnClickListener, SearchUserListHolder.OnItemClickListener, TextWatcher {
    private static final String TAG = "CompanySearchActivity";
    @BindView(R.id.search_member_txt)
    EditText searchTxt;
    @BindView(R.id.search_list)
    RecyclerView searchList;
    @BindView(R.id.recycler_title)
    TextView titleText;
    private SearchUserListHolder userListAdapter;
    private List<SearchHistoryBean> userList;
    private SearchRepository mSearchRepository;

    @BindView(R.id.error_content)
    RelativeLayout errorLayout;
    @BindView(R.id.content_layout)
    NestedScrollView contentLayout;

    private Subscription requestSub;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initBaseView();
        requestLocalData();
    }

    private void requestLocalData() {
        mSearchRepository.searchUserLimit(10, new SearchDataSourse.GetSearchCallback() {
            @Override
            public void onUserLoaded(SearchHistoryBean search) {

            }

            @Override
            public void onSearchDataArray(List<SearchHistoryBean> beans) {
                userList.clear();
                userList.addAll(beans);
                userListAdapter.setShowFork(true);
                if (userList.size() > 0) {
                    errorLayout.setVisibility(View.INVISIBLE);
                    contentLayout.setVisibility(View.VISIBLE);
                    if (userListAdapter != null)
                        userListAdapter.notifyDataSetChanged();
                } else {
                    errorLayout.setVisibility(View.VISIBLE);
                    contentLayout.setVisibility(View.INVISIBLE);
                    errorLayout.addView(ErrorViewCreateUtils.createNoSearchView(getActivityContext()));
                }
            }

            @Override
            public void onDataNotAvailable() {

            }
        });
    }


    private void initData() {
        mSearchRepository = ModelProvider.provideSearchRepository();
        userList = new ArrayList<>();
    }


    private void initBaseView() {
        ManageDividerItemDecoration dividerDecoration = new ManageDividerItemDecoration(this, ManageDividerItemDecoration.VERTICAL_LIST, 5, true);
        dividerDecoration.setBaseFloat(0.3f);
        //团队的list
        userListAdapter = new SearchUserListHolder(this, userList);
        searchList.setNestedScrollingEnabled(false);
        searchList.setHasFixedSize(true);
        searchList.setLayoutManager(new LinearLayoutManager(this));
        searchList.setItemAnimator(new DefaultItemAnimator());
        searchList.addItemDecoration(dividerDecoration);
        searchList.setAdapter(userListAdapter);
        userListAdapter.setOnItemClickListener(this);

        searchTxt.addTextChangedListener(this);

    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_company_search_layout;
    }


    @OnClick({R.id.arrow_right, R.id.search_btn})
    @Override
    public void onClick(View v) {
        switch ((v.getId())) {
            case R.id.arrow_right:
                super.onBackPressed();
                break;
            case R.id.search_btn:
                //点击搜索按钮
                break;
        }
    }

    @Override
    public void onItemClick(View view, int position, int listType) {
        switch (listType) {
            case SearchUserListHolder.TYPE_USER_CLICK:
                //点击用户
                SearchHistoryBean addBean = userList.get(position);
                mSearchRepository.saveSearchData(addBean);
                IntentUtils.startActivityWithString(PersonUserBean.USER_ID_KEY, userList.get(position).getUserId(), this, CompanyUserDetailsMsgActivity.class);
                break;
            case SearchUserListHolder.TYPE_DELETE_CLICK:
                //点击删除
                SearchHistoryBean deleteBean = userList.get(position);
                userList.remove(position);
                mSearchRepository.deleteSearchData(deleteBean);
                userListAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //打字的逻辑写在此处
        if (!TextUtils.isEmpty(s.toString())) {
            if (titleText.getVisibility() == View.VISIBLE)
                titleText.setVisibility(View.GONE);
            NaizhuAILog.e("CharSequence=" + s + "start=" + start + ";before=" + before + ";count=" + count);
            requestSearchData(s);
        } else {
            titleText.setVisibility(View.VISIBLE);
            requestLocalData();
        }

    }

    private void requestSearchData(CharSequence s) {
        errorLayout.setVisibility(View.VISIBLE);
        contentLayout.setVisibility(View.INVISIBLE);
        errorLayout.addView(ErrorViewCreateUtils.createLoadingView(this));
        String companyId = getShareValue(CompanyBean.COMPANY_ID_KEY, "");
        if (!TextUtils.isEmpty(companyId)) {
            requestSub = PublicDataApiStoreIml.getInstance().getThankPeople(s.toString()).subscribe(new Observer<List<VirtualChosenBean>>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    hideWaitDialog();
                    errorLayout.setVisibility(View.VISIBLE);
                    contentLayout.setVisibility(View.INVISIBLE);
                    errorLayout.addView(ErrorViewCreateUtils.createNoNetworkView(getActivityContext(), v -> requestSearchData(s)));
                }

                @Override
                public void onNext(List<VirtualChosenBean> personUserBeans) {
                    hideWaitDialog();
                    List<SearchHistoryBean> searchBeans = new ArrayList<>();
                    for (VirtualChosenBean userBean : personUserBeans) {
                        SearchHistoryBean search = new SearchHistoryBean(userBean.getSelectedId(), userBean.getUserThumb(), userBean.getName(), new Date().getTime());
                        searchBeans.add(search);
                    }
                    userList.clear();
                    userList.addAll(searchBeans);
                    if (userList.size() > 0) {
                        errorLayout.setVisibility(View.INVISIBLE);
                        contentLayout.setVisibility(View.VISIBLE);
                        userListAdapter.setShowFork(false);
                        userListAdapter.notifyDataSetChanged();
                    } else {
                        errorLayout.setVisibility(View.VISIBLE);
                        contentLayout.setVisibility(View.INVISIBLE);
                        errorLayout.addView(ErrorViewCreateUtils.createNoSearchView(getActivityContext()));
                    }
                }
            });
        }
    }

    @Override
    public void onBackPressedWithoutDialog() {
        if (requestSub != null && !requestSub.isUnsubscribed()) {
            DialogUtils.showSureDialog(this, getString(R.string.cancel_submit_request), new View.OnClickListener() {
                @Override
                public void onClick(View dialog) {
                    requestSub.unsubscribe();
                    errorLayout.setVisibility(View.VISIBLE);
                    errorLayout.removeAllViews();
                    errorLayout.addView(ErrorViewCreateUtils.createNoNetworkView(getActivityContext(), v -> {
                        requestSearchData(searchTxt.getText());
                    }));
                }
            });
        } else {
            super.onBackPressedWithoutDialog();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}